package com.haozi.core;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.haozi.config.GlobalConfig;
import com.haozi.constants.ConfigConstant;
import com.haozi.dto.PointResult;
import com.haozi.event.GetPointAfterEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @author zyh
 * @version 1.0
 * @date 2022/4/29 3:13 下午
 */
@Component
@Slf4j
public class AndRemind implements ApplicationListener<GetPointAfterEvent> {


    @Autowired
    DingDingDataHandler dingDingDataHandler;
    @Autowired
    GlobalConfig globalConfig;
    /**
     * 上次点数
     */
    BigDecimal lastPoint;

    @Override
    public void onApplicationEvent(GetPointAfterEvent event) {

        PointResult pointResult = event.getPointResult();
        if (lastPoint == null) {
            lastPoint = pointResult.getCurrentPoint();
        }
        BigDecimal subtract = pointResult.getCurrentPoint().subtract(lastPoint);

        log.debug("当前点数{},较之前浮动点数{}", pointResult.getCurrentPoint().toPlainString(), subtract.toPlainString());

        String thresholdPointStr = globalConfig.getProperties(ConfigConstant.THRESHOLD_POINT);
        BigDecimal thresholdPoint = BigDecimal.TEN;
        if (NumberUtil.isNumber(thresholdPointStr)) {
            thresholdPoint = new BigDecimal(thresholdPointStr);
        }
        //起伏小于阈值不做处理
        if (thresholdPoint.compareTo(subtract.abs()) > 0) {
            return;
        }

        try {
            dingDingDataHandler.sendMesg("涨幅大于设定阈值"
                    , StrUtil.format("提醒:浮动点数{},当前点数{},", subtract.toPlainString(), pointResult.getCurrentPoint().toPlainString()));
        } catch (Exception ex) {
            log.error("消息发送失败" + ex.getMessage());
        }

        lastPoint = pointResult.getCurrentPoint();
    }


}
